/**
 * Created by status200 on 2017/7/31.
 */


var app = angular.module("register", ["ngCookies", "makerspace.component","makerspace.util","ngRap"]);

// 团队数据
app.service("teamData", ["$cookies","uuidv4",function ($cookies,uuidv4) {

    // 每个字段都有一个value和valid属性
    // value是该字段的值
    // valid是指示该字段是否符合要求,设立该属性是为了表单提交便于验证

    // 测试时用
    // return {
    //     teamId: {
    //         value: uuidv4(),
    //         valid: true
    //     },
    //     teamName: {
    //         value: "TPW工作室",
    //         valid: true
    //     },
    //     projectName: {
    //         value: "演武创客空间",
    //         valid: true
    //     },
    //     belongField: {
    //         value: "金融业",
    //         valid: true
    //     },
    //     projectType: {
    //         value: "自选",
    //         valid: true
    //     },
    //     members: [
    //         {
    //             studentName: {
    //                 value: "黄一鑫",
    //                 valid: true
    //             },
    //             college: {
    //                 value: "软件学院",
    //                 valid: true
    //             },
    //             studentId: {
    //                 value: "24320152202752",
    //                 valid: true
    //             },
    //             educationBackground: {
    //                 value: "本科",
    //                 valid: true
    //             },
    //             phoneNumber: {
    //                 value: "15392035361",
    //                 valid: true
    //             },
    //             email: {
    //                 value: "358941501@qq.com",
    //                 valid: true
    //             },
    //             removeAble: false
    //         }
    //     ],
    //     projectBrief: {
    //         value: "sss",
    //         valid: true
    //     },
    //     projectDirector: {
    //         value: "sss",
    //         valid: true
    //     },
    //     workFoundation: {
    //         value: "ddd",
    //         valid: true
    //     },
    //     plan: {
    //         value: "ddd",
    //         valid: true
    //     },
    //     files: []
    // };

    return {
        teamId: {
            value: uuidv4(),
            valid: true
        },
        teamName: {
            value: "",
            valid: false
        },
        projectName: {
            value: "",
            valid: false
        },
        belongField: {
            value: "",
            valid: false
        },
        projectType: {
            value: "",
            valid: false
        },
        members: [
            {
                studentName: {
                    value: "",
                    valid: false
                },
                college: {
                    value: "",
                    valid: false
                },
                studentId: {
                    value: "",
                    valid: false
                },
                educationBackground: {
                    value: "",
                    valid: false
                },
                phoneNumber: {
                    value: "",
                    valid: false
                },
                email: {
                    value: "",
                    valid: false
                },
                removeAble: false
            }
        ],
        projectBrief: {
            value: "",
            valid: false
        },
        projectDirector: {
            value: "",
            valid: false
        },
        workFoundation: {
            value: "",
            valid: false
        },
        plan: {
            value: "",
            valid: false
        },
        files: []
    }
}]);

app.service("checkBeforeSubmit", function (teamData) {

    console.log(teamData);
    // 检查所有字段是否都合法
    return function () {
        for (var i in teamData) {
            if (i === "members") {
                for (var j in teamData[i]) {
                    for (var k in teamData[i][j])
                        if ("valid" in teamData[i][j] && !teamData[i][j][k].valid) {
                            console.log("illegal field:members[", j, "]", k);
                            alert("存在不符合规定或为空的字段");
                            return false;
                        }
                }
            } else {
                if ("valid" in teamData[i] && !teamData[i].valid) {
                    console.log("illegal field:", i);
                    alert("存在不符合规定或为空的字段");
                    return false;
                }
            }
        }

        // TODO:检验成员学号是否重复
        var tempObj = [];
        for(var i in teamData.members) {
            var stuId = teamData.members[i].studentId.value;
            if(tempObj.indexOf(stuId) >= 0) {
                alert("成员学号重复");
                return false;
            }
            tempObj.push(stuId);
        }

        // 检查文件的上传状态
        // TODO:未设置样例进行测试
        for (var i in teamData.files) {
            if (!teamData.files[i].isDone) {
                console.log("illegal field:files");
                alert("请等所有文件上传完毕再提交.");
                return false;
            }

            if(!teamData.files[i].isSuccess) {
                console.log("illegal field:files");
                alert("存在上传失败的文件.请先移除.");
                return false;
            }
        }

        if (teamData.files.length === 0) {
            console.log("illegal field:files");
            alert("请至少上传一个文件.");
            return false;
        }

        return true;
    };
});

// 必须先注入angular预设的服务，最后才是自定义的服务
app.controller("form-controller", ["$scope", "$http", "teamData", "checkBeforeSubmit", "FileUploader",
    function ($scope, $http, teamData, checkBeforeSubmit, FileUploader) {
        $scope.teamData = teamData;
        $scope.belongFields = [
            "农、林、牧、渔业",
            "采矿业",
            "制造业",
            "电力、热力、燃气及水生产和供应业",
            "建筑业",
            "批发和零售业",
            "交通运输、仓储和邮政业",
            "住宿和餐饮业",
            "信息传输、软件和信息技术服务业",
            "金融业",
            "房地产业",
            "租赁和商务服务业",
            "科学研究和技术服务业",
            "水利、环境和公共设施管理业",
            "居民服务、修理和其它服务业",
            "教育",
            "卫生和社会工作",
            "文化、体育和娱乐业",
            "公共管理、社会保障和社会组织",
            "国际组织"
        ];

        $scope.projectTypes = [
            "竞赛",
            "自选"
        ];

        // 添加成员
        $scope.addMember = function () {
            $scope.teamData.members.push({
                studentName: {
                    value: "",
                    valid: false
                },
                college: {
                    value: "",
                    valid: false
                },
                studentId: {
                    value: "",
                    valid: false
                },
                educationBackground: {
                    value: "",
                    valid: false
                },
                phoneNumber: {
                    value: "",
                    valid: false
                },
                email: {
                    value: "",
                    valid: false
                },
                removeAble: true
            });
        };

        // 移除成员
        // 该方法传给<member>指令调用
        $scope.removeMember = function (index) {
            if (confirm("确定要移除吗?")) {
                $scope.teamData.members.splice(index, 1);
            }
        };

        // 提交按钮操作,会对所有字段进行检查
        $scope.submit = function () {

            if (checkBeforeSubmit() && confirm("确定提交吗")) {
                var submitData = {
                    teamId: teamData.teamId.value,
                    teamName: teamData.teamName.value,
                    projectName: teamData.projectName.value,
                    belongField: teamData.belongField.value,
                    projectType: teamData.projectType.value,
                    members: [],
                    projectBrief: teamData.projectBrief.value,
                    projectDirector: teamData.projectDirector.value,
                    workFoundation: teamData.workFoundation.value,
                    plan: teamData.plan.value
                };

                // 设置成员
                teamData.members.forEach(function (el, i) {
                    var arr = teamData.members;
                    console.log(arr);
                    submitData.members.push({
                        teamId: teamData.teamId.value,
                        orderInTeam: i + 1,
                        studentName: arr[i].studentName.value,
                        college: arr[i].college.value,
                        studentId: arr[i].studentId.value,
                        educationBackground: arr[i].educationBackground.value,
                        phoneNumber: arr[i].phoneNumber.value,
                        email: arr[i].email.value
                    })
                });

                console.log(submitData);

                $http({
                    method: "POST",
                    url: requestRootUrl + "api/register/submit",
                    data: angular.toJson(submitData)
                }).then(
                    function success(resp) {
                        alert("提交成功!\n您团队的查询验证码已经发送到负责人邮箱,该验证码可以用来修改入驻信息.");
                        window.location.href = successRedirectUrl;
                    },
                    function error(resp) {
                        alert("服务器异常");
                    });

            }
        };

        // 配置fileUploader参数
        $scope.fileUploader = new FileUploader({
            uploadUrl: requestRootUrl + "api/register/upload-file",
            deleteUrl: requestRootUrl + "api/register/delete-file",
            maxSize: 50 * 1024 * 1024,
            filter: [
                ".doc", ".docx", ".pdf", ".mp3", ".mp4", ".rar", ".zip"
            ]
        });


        $scope.teamData.files = $scope.fileUploader.files;

        // 文件上传时需要添加的团队id参数
        $scope.paramsWithFileUpload = {
            teamId:$scope.teamData.teamId.value
        }
    }]);

// 团队名输入表单，带有后台验证和空检查
app.directive("inputWithValidateAndNullCheck", ["$http", "$timeout","teamData",
    function ($http, $timeout,teamData) {
    return {
        restrict: "AE",
        scope: {
            label: '@',
            model: '='
        },
        replace: false,
        transclude: false,
        template: "<div class='form-group'>"
        + "<label class='col-xs-2 control-label text-inkblue'><span class='star'>*</span>{{label}}:</label>"
        + "<div class='col-xs-9'>"
        + "<input type='text' ng-model='model.value' class='form-control basic-info' placeholder='请输入您的团队名称' ng-required='true'/>&nbsp;"
        + "<span class='text-feedback'>{{hint}}</span>"
        + "</div>"
        + "</div>",
        link: function (scope, element, attrs) {
            scope.hint = "";

            var timeout;
            // 监控model改变
            scope.$watch("model.value", function (newModel) {

                // 每次改变先取消掉定时器,防止多次触发对后台的请求
                if (timeout) {
                    $timeout.cancel(timeout);
                }

                // 如果model不为空,向后台发起请求
                if (newModel) {
                    scope.hint = "";

                    // 设置一个定时器,只有当停止连续输入时,才对后台发起请求
                    timeout = $timeout(function () {
                        console.log("start to validate name...");
                        $http({
                            method: "POST",
                            url: requestRootUrl + "api/register/validate-team-name",
                            // CAUTION:注意这里的数据格式
                            data: {
                                teamName: scope.model.value,
                                teamId:teamData.teamId.value
                            },
                            headers: {
                                "Content-Type": "application/json"
                            }
                        }).then(function (resp) {
                            // CAUTION:注意这里的数据格式
                            // 返回数据是指示了是否有重复
                            console.log("validate name get result:");
                            console.log(resp);
                            if (!resp.data.valid) {
                                scope.hint = "团队名重复!";
                                scope.model.valid = false;
                            } else {
                                scope.hint = "";
                                scope.model.valid = true;
                            }

                        });
                    }, 500);// 改变这边的参数可以改变间隔
                } else {
                    scope.hint = "团队名不能为空!";
                    scope.model.valid = false;
                }
            });
        }
    }
}]);

// 只带有空检查的表单
app.directive("inputWithNullCheck", function () {
    return {
        restrict: "AE",
        scope: {
            label: '@',
            model: '='
        },
        replace: false,
        transclude: false,
        template: "<div class='form-group'>"
        + "<label class='col-xs-2 control-label text-inkblue'><span class='star'>*</span>{{label}}:</label>"
        + "<div class='col-xs-9'>"
        + "<input type='text' ng-model='model.value' class='form-control basic-info' placeholder='请输入您的{{label}}' ng-required='true'/>&nbsp;"
        + "<span class='text-feedback'>{{hint}}</span>"
        + "</div>"
        + "</div>",
        link: function (scope, element, attrs) {
            scope.hint = "";
            scope.$watch("model.value", function (newModel) {

                if (!newModel) {
                    scope.hint = scope.label + "不能为空!";
                    scope.model.valid = false;
                } else {
                    scope.hint = "";
                    scope.model.valid = true;
                }
            });
        }
    }
});

// 多选框
app.directive("selectWithNullCheck", function () {
    return {
        restrict: "AE",
        scope: {
            label: '@',
            model: '=',
            options: '='
        },
        replace: false,
        transclude: false,
        template: "<div class='form-group'>"
        + "<label class='col-xs-2 control-label text-inkblue'><span class='star'>*</span>{{label}}:</label>"
        + "<div class='col-xs-9'>"
        + "<select class='form-control basic-info' ng-options='option for option in options' ng-model='model.value' required>"
        + "</select>"
        + "&nbsp;"
        + "<span class='text-feedback'>{{hint}}</span>"
        + "</div>"
        + "</div>",
        link: function (scope, element, attrs) {
            scope.hint = "";
            scope.$watch("model.value", function (newModel) {
                if (!newModel) {
                    scope.hint = scope.label + "不能为空!";
                    scope.model.valid = false;
                } else {
                    scope.hint = "";
                    scope.model.valid = true;
                }
            });
        }

    }
});

app.directive("member", function () {
    return {
        restrict: "AE",
        replace: false,
        transclude: false,
        scope: {
            model: "=",
            remove: "&"
        },
        template: "<div aria-label='one-member'>" +
        "<div class='members-line'>" +
        "<div class='members-grid'><input type='text' class='form-control' ng-model='model.studentName.value'></div>" +
        "<div class='members-grid '><input type='text' class='form-control' ng-model='model.college.value'></div>" +
        "<div class='members-grid '><input type='text' class='form-control' ng-model='model.studentId.value'></div>" +
        "<div class='members-grid '>" +
        "<select class='form-control' ng-model='model.educationBackground.value'>" +
        "<option></option>" +
        "<option>本科</option>" +
        "<option>硕士</option>" +
        "<option>博士</option>" +
        "</select>" +
        "</div>" +
        "<div class='members-grid '><input type='text' class='form-control' ng-model='model.phoneNumber.value'></div>" +
        "<div class='members-grid '><input type='text' class='form-control' ng-model='model.email.value'></div>" +
        "<div class='members-grid' ng-if='model.removeAble'><span class='remove-member' ng-click='remove()'>移除</span></div>" +
        "</div>" +
        "<div class='members-line'>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[0]}}</span></div>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[1]}}</span></div>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[2]}}</span></div>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[3]}}</span></div>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[4]}}</span></div>" +
        "<div class='members-grid'><span class='text-feedback hint'>{{hint[5]}}</span></div>" +
        "</div>" +
        "</div>",
        link: function (scope, element, attr) {

            // MARK:成员信息字段格式在这里
            var patterns = [
                /^([A-Za-z\u4E00-\u9FA5]){1,20}$/,
                /^[\u4E00-\u9FA5]{1,10}学院$/,
                /^[0-9]{14}$/,
                null,
                /^1[0-9]{10}$/,
                /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
            ];

            scope.hint = [
                "",
                "",
                "",
                "",
                "",
                ""
            ];

            var checkModel = function (modelName, index, hintString) {

                scope.$watch("model." + modelName + ".value", function (newVal) {
                    if (!newVal) {
                        scope.hint[index] = "不能为空";
                        scope.model[modelName].valid = false;
                        return;
                    }

                    if (patterns[index] && !patterns[index].exec(newVal)) {
                        scope.hint[index] = hintString;
                        scope.model[modelName].valid = false;
                        return;
                    }

                    scope.hint[index] = "";
                    scope.model[modelName].valid = true;
                });
            };

            checkModel("studentName", 0, "必须为不超过20个字符的中文或英文");
            checkModel("college", 1, "请输入厦大的一个学院");
            checkModel("studentId", 2, "请输入正确格式的学号");
            checkModel("educationBackground", 3, "");
            checkModel("phoneNumber", 4, "请输入正确格式的手机号");
            checkModel("email", 5, "格式不正确");

        }
    }
});

app.directive("textareaWithNullCheck", function (teamData) {

    return {
        restrict: "AE",
        replace: false,
        transclude: false,
        scope: {
            label: "@",
            model: "="
        },
        template: "  <div class='form-group'>" +
        "                <label class='col-xs-2 control-label text-inkblue'><span class='star'>*</span>{{label}}:</label>" +
        "                <textarea rows='10' class='form-control introduction-info'" +
        "                          placeholder='请输入您的{{label}}' ng-model='model.value'></textarea>" +
        "               <span class='text-feedback'>{{hint}}</span>" +
        "            </div>",
        link: function (scope, element, attrs) {
            scope.$watch("model.value", function (newValue) {

                if (!newValue) {
                    scope.hint = "不能为空";
                    scope.model.valid = false;
                    return;
                }

                scope.hint = "";
                scope.model.valid = true;
            });
        }
    }
});